package com.maixy.studyonlineapi.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.maixy.studyonlineapi.constants.GlobalConstant;
import com.maixy.studyonlineapi.exceptions.TokenException;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author mai
 */
public class JwtUtils {

    /**
     * 定义一串密钥用于token加密解密
     */
    private static final String secret = "team";
    /**
     * 签发人
     */
    private static final String issuer = "team";
    /**
     * 接收人
     */
    private static final String Audience = "team";
    /**
     * authorization有效时间为1年
     */
    private static final long expTime = GlobalConstant.Times.ONE_YEAR * 1000;

    /**
     * 设置一般的Authorization
     *
     * @param userId     用户id
     * @param username   用户名
     * @param password   密码
     * @param openid     微信小程序的openid
     * @param sessionKey 微信小程序的sessionKey
     * @return token
     */
    public static String createToken(Long userId, Integer roleType, String username, String password, String openid, String sessionKey) {
        Map<String, Object> header = new HashMap<>();
        header.put("alg", "HS256");
        header.put("typ", "JWT");
        return JWT.create()
                .withHeader(header)
                .withIssuer(issuer)
                .withAudience(Audience)
                .withClaim("userId", userId)
                .withClaim("roleType", roleType)
                .withClaim("username", username)
                .withClaim("password", password)
                .withClaim("openid", openid)
                .withClaim("sessionKey", sessionKey)
                .withIssuedAt(new Date())
                .withExpiresAt(new Date(System.currentTimeMillis() + expTime))
                .sign(Algorithm.HMAC256(secret));
    }

    /**
     * study-online-api的Authorization
     *
     * @param userId     用户id
     * @param username   用户名
     * @param nickName     昵称
     * @param avatarUrl 头像
     * @return token
     */
    public static String createToken(Long userId, String username, String nickName, String avatarUrl) {
        Map<String, Object> header = new HashMap<>();
        header.put("alg", "HS256");
        header.put("typ", "JWT");
        return JWT.create()
                .withHeader(header)
                .withIssuer(issuer)
                .withAudience(Audience)
                .withClaim("userId", userId)
                .withClaim("username", username)
                .withClaim("nickName", nickName)
                .withClaim("avatarUrl", avatarUrl)
                .withIssuedAt(new Date())
                .withExpiresAt(new Date(System.currentTimeMillis() + expTime))
                .sign(Algorithm.HMAC256(secret));
    }

    /**
     * 验证令牌
     *
     * @param token 令牌
     */
    public static void verityToken(String token) {
        JWTVerifier jwtVerify = JWT.require(Algorithm.HMAC256(secret)).build();
        try {
            jwtVerify.verify(token);
        } catch (Exception e) {
            throw new TokenException();
        }
    }

    /**
     * 获取JWT携带的用户名
     * @param token
     * @return
     */
    public String getUsername(String token) {
        return JWT.decode(token).getClaim("username").asString();
    }

}
